package cn.xspace.library.view.dialog;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.TextView;

import com.xspace.android.xafcommon.util.CalendarUtil;
import com.xspace.android.xafcommon.util.CustomDate;
import com.xspace.android.xafcommon.util.T;

import cn.xspace.library.R;
import cn.xspace.library.view.dialog.calendar.CalendarCard;
import cn.xspace.library.view.dialog.calendar.CalendarViewAdapter;

/**
 * Wubj 创建于 2017/2/22.
 */
public class DatePickerDialog extends Dialog implements CalendarCard.OnCellClickListener {

    private final Context mContext;
    private ViewPager mViewPager;
    private TextView showYearView;
    private TextView showMonthView;
    private TextView currentDay;
    private int mCurrentIndex = 498;
    private CalendarCard[] mShowViews;
    private CalendarViewAdapter<CalendarCard> adapter;
    private SlideDirection mDirection = SlideDirection.NO_SLIDE;
    private int measuredHeight;

    private enum SlideDirection {
        RIGHT, LEFT, NO_SLIDE
    }

    private onDateClickListener listener;

    public void setListener(onDateClickListener listener) {
        this.listener = listener;
    }

    public interface onDateClickListener {
        void dateClick(CustomDate date);
    }

    private DatePickerDialog(Context context, int theme) {
        super(context, theme);
        mContext = context;
        this.setContentView(R.layout.dialog_date_picker);
        this.setCanceledOnTouchOutside(true);
        findView();
    }

    private void findView() {
        mViewPager = (ViewPager) this.findViewById(R.id.vp_calendar);
        showMonthView = (TextView) this.findViewById(R.id.show_month_view);
        showYearView = (TextView) this.findViewById(R.id.show_year_view);
        currentDay = (TextView) this.findViewById(R.id.turn_current_day);
        currentDay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                returnCurrentMonth();
            }
        });

        CalendarCard[] views = new CalendarCard[3];
        for (int i = 0; i < 3; i++) {
            views[i] = new CalendarCard(mContext, this);
        }
        //动态设置ViewPager高度
        final CalendarCard finalView = views[0];
        finalView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                measuredHeight = finalView.getMeasuredHeight();
                Log.e("wubaojie", "onGlobalLayout: " + measuredHeight);
                ViewGroup.LayoutParams layoutParams = mViewPager.getLayoutParams();
                layoutParams.height = measuredHeight;
                mViewPager.setLayoutParams(layoutParams);
                // 宽高已经测量完毕,执行获取宽高的操作
                finalView.getViewTreeObserver().removeGlobalOnLayoutListener(this);//操作完毕关闭监听
            }
        });

        adapter = new CalendarViewAdapter<>(views);
        setViewPager();
    }

    private void setViewPager() {
        mViewPager.setAdapter(adapter);
        mViewPager.setCurrentItem(498);
        mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                measureDirection(position);
                updateCalendarView(position);
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
//                dayMap.clear();
            }
        });
    }

    @Override
    public void clickDate(CustomDate date) {
        if (listener != null) {
            if ((CalendarUtil.getYear() == date.year && date.month > CalendarUtil.getMonth()) //本年但是大于当前月
                    || date.year > CalendarUtil.getYear()) { //以后的年
                T.showSingleL("还未到达的日期");
            } else {
                listener.dateClick(date);
                dismiss();
            }
        }
    }

    @Override
    public void changeDate(CustomDate date) {
        showYearView.setText(date.year + "年");
        showMonthView.setText(date.month + "月");
    }

    /**
     * 计算方向
     *
     * @param position
     */
    private void measureDirection(int position) {
        if (position > mCurrentIndex) {
            mDirection = SlideDirection.RIGHT;
        } else if (position < mCurrentIndex) {
            mDirection = SlideDirection.LEFT;
        }
        mCurrentIndex = position;
    }

    // 更新日历视图
    private void updateCalendarView(int position) {
        mShowViews = adapter.getAllItems();
        if (mDirection == SlideDirection.RIGHT) {
            mShowViews[position % mShowViews.length].nextMonth();
        } else if (mDirection == SlideDirection.LEFT) {
            mShowViews[position % mShowViews.length].lastMonth();
        }
        mDirection = SlideDirection.NO_SLIDE;
    }

    private void returnCurrentMonth() {
        mShowViews = adapter.getAllItems();
        if (mShowViews != null) {
            int currentItem = mViewPager.getCurrentItem();
            mShowViews[currentItem % mShowViews.length].currentMonth();
            mDirection = SlideDirection.NO_SLIDE;
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (!hasFocus) {
            dismiss();
        }
    }

    public static class Builder {
        DatePickerDialog mDatePickerDialog;

        public Builder(Context context, int theme) {
            mDatePickerDialog = new DatePickerDialog(context, theme);
        }

        public Builder(Context context) {
            this(context, R.style.CustomDialog);
        }

        public DatePickerDialog build() {
            return mDatePickerDialog;
        }
    }


}
